//获取应用实例
var app = getApp();
//获得

var MyRequest = require("../../utils/MyRequest.js");
var Global = require("../../Global.js");
var LocalCart = require("../../LocalCart.js");

Page({
    data:{
        isFrom:"mine",
        Page: 1,
        Count: 8,
    },
    Presenter:{
        init:function(that){
            that.setData({Page:1})
            var data = {userId: Global.getUserStorage().id,begin:0,end:that.data.Page*that.data.Count };
      MyRequest.MyGetWithRefresh("NoTimeOutCouponList", that,that.Binder.init,data);
        },
        Pull:function(that){
            var page = that.data.Page+1;
            that.setData({Page:page})
               var data = {userId: Global.getUserStorage().id,begin:0,end:that.data.Page*that.data.Count };
      MyRequest.MyGetWithToast("NoTimeOutCouponList", that,that.Binder.init,data);
        }
    },
    Binder:{
        init:function(result,that){
            if(!result.data){
                return;
            }
            var data = result.data.data;
            var d = new Array();
            for(var i=0;i<data.length;i++){
                if(data[i].isTimeout == 0){
                    var rules = data[i].rule.split("|");
                    data[i].rules = rules;
                    data[i].state = "hide"; 
                    d[d.length] = data[i];
                }
            }
            
             
            that.setData({
                coupons:d
            });
        }
    },
    onLoad:function(options){
        if(options.from){
            this.setData({
                isFrom:options.from,
                TotalPrice:options.TotalPrice
            });
        }
        this.Presenter.init(this);
    },
    onRuleCLick:function(event){
        var index = event.currentTarget.dataset.index;
        var data = this.data.coupons;
        var state = data[index].state;
        if(state == "hide"){
            state = "show";
        }else{
            state = "hide";
        }
        data[index].state = state;
        this.setData({
            coupons:data
        });
    },
    onReachBottom: function () {
       this.Presenter.Pull(this);
    },
    onPullDownRefresh:function(){
        this.Presenter.init(this);
    },
    onItemClick:function(event){
        if(this.data.isFrom == "cart"){
            var index = event.currentTarget.dataset.index;
     
            if(this.data.TotalPrice <= this.data.coupons[index].conditions){
                wx.showToast({
                    title: '无法使用该优惠券',
                    duration: 1000
                })
                return;
            }
            LocalCart.setCouponStorage(this.data.coupons[index]);
  
             wx.navigateBack();
    
        }
    }
})